package com.xincheng.library.util;

import java.io.File;
import java.io.FileInputStream;
import java.text.DecimalFormat;

/**
 * Created by xiaote on 2017/7/10.
 */

public class FileUtil {
    public static final String DEFAULT_FILE_SIZE = "0B";

    public static long getFileSize(File file) throws Exception {
        long size = 0;
        if (file.exists() && file.isFile()) {
            FileInputStream fis = null;
            fis = new FileInputStream(file);
            size = fis.available();
        }
        return size;
    }

    public static long getFileSizes(File file) throws Exception {
        long size = 0;
        if(file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                if(files[i].isFile()) {
                    size += getFileSize(files[i]);
                }
            }
        }
        return size;
    }

    public static String formatFileSize(long fileSize) {
        DecimalFormat df = new DecimalFormat("0.00");
        String fileSizeString = "";
        String wrongSize = "0B";
        if (fileSize == 0) {
            return wrongSize;
        }
        if (fileSize < 1024) {
            fileSizeString = df.format((double) fileSize) + "B";
        } else if (fileSize < 1024 * 1024) {
            fileSizeString = df.format((double) fileSize / 1024) + "KB";
        } else if (fileSize < 1024 * 1024 * 1024) {
            fileSizeString = df.format((double) fileSize / 1048576) + "MB";
        } else {
            fileSizeString = df.format((double) fileSize / 1073741824) + "GB";
        }
        return fileSizeString;
    }

    public static void deleteFiles(File file) {
        if(file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                if(files[i].isFile() && files[i].exists()) {
                    files[i].delete();
                }
            }
        }
    }
}


